package org.rudenko.horo;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;


public class ViewPageActivity extends Activity {
	
	public static String TODAY;
	public static String TOMORROW;
	public static String YESTERDAY;
	public static String WEEK;
	public static String MONTH;
	public static String curDay;
	public static String curType;
	private static int signId;
    public TextView cont;
	protected static String ID;
	static final int OPEN_DIALOG = 0;
	static final int INET_CON = 1;
	public static String[] k;
	
	private final static String[] SIGNS = {"aries","taurus","gemini","cancer","leo","virgo","libra",
			"scorpio","sagittarius","capricorn","aquarius","pisces"};		
	
    public void onCreate(Bundle savedInstanceState) {
    	Bundle extras = getIntent().getExtras();
    	signId = extras.getInt(ID); 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_view_layout);
        getDates();
        
        cont = (TextView)findViewById(R.id.cont);
        cont.setMovementMethod(new ScrollingMovementMethod());
        
        Spinner spin = (Spinner) findViewById(R.id.spnr);        
        String spnVal[] = getResources().getStringArray(R.array.spnr);         
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item
        		,spnVal) ;
        
        arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spin.setAdapter(arrayAdapter);
        spin.setSelection(1);
        spin.setOnItemSelectedListener(new OnItemSelectedListener(){

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				curType="";
				switch(arg2){
		    	case 0: curDay=YESTERDAY;
		    	break;
		    	case 1: curDay=TODAY;   
		    	break;
		    	case 2: curDay=TOMORROW; 
		    	break;	
		    	case 3: curDay=WEEK; curType="type=weekly"; 
		    	break;
		    	case 4: curDay=MONTH; curType="type=monthly"; 
		    	break; 
		    	}
				Log.d("app","sign="+SIGNS[signId]+"date="+curDay+curType);
				new AsyncGetHoroscop().execute("sign="+SIGNS[signId],"date="+curDay,curType);
			}

			public void onNothingSelected(AdapterView<?> arg0) {		
			}
        	
        });
                
/////////////////////////END ONCREATE/////////////////////////////////////////        
    }
    
 
    public void onConfigurationChanged(Configuration newConfig) {  
        super.onConfigurationChanged(newConfig);  
    }
 
    protected Dialog onCreateDialog(int id)
	{
    	switch (id) 
		{
		case OPEN_DIALOG:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Choose to open");
			builder.setCancelable(true);
			builder.setItems(k, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				DbAction oda = new DbAction(getApplicationContext(),"save");
				cont.setText(oda.getFromDb(k[which]));				
				}
			});
            return builder.create();
		case INET_CON: 
			AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
			builder2.setTitle(getResources().getText(R.string.dlg2_ttl).toString());
			builder2.setCancelable(false);
			builder2.setMessage(getResources().getText(R.string.dlg2_chckcon).toString());
			builder2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
			dialog.dismiss();
				}
			});
			return builder2.create();   
		default:
			return null;
		}
    }
    
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu, menu);
//copy to clipboard        
        menu.getItem(2).setOnMenuItemClickListener(new OnMenuItemClickListener(){
			public boolean onMenuItemClick(MenuItem item) {
				copyToClipboard();
				return false;
			}        
        });
//save  
        menu.getItem(1).setOnMenuItemClickListener(new OnMenuItemClickListener(){
			public boolean onMenuItemClick(MenuItem item) {
				DbAction sda= new DbAction(getApplicationContext(), "save");
				String params = SIGNS[signId].concat(" "+curDay);
				if(curType.equals("type=weekly")) params = params.concat(" W");
				if(curType.equals("type=monthly")) params = params.concat(" M");
				if(sda.getFromDb(params)=="")sda.addToDb(params, cont.getText().toString());
				removeDialog(OPEN_DIALOG);
				return false;
			}        
        });
//save end

//open  
        menu.getItem(0).setOnMenuItemClickListener(new OnMenuItemClickListener(){
			public boolean onMenuItemClick(MenuItem item) {
				DbAction oda= new DbAction(getApplicationContext(), "save");
				k = oda.getDbKeys();
				showDialog(OPEN_DIALOG);		        
			return false;
			}        
        });
//open end
        return true;
    }
        
    private String getDates(){
    	final String timePattern = "yyyy-MM-dd";
        final SimpleDateFormat dateFormatter =  new SimpleDateFormat(timePattern);
        final SimpleDateFormat dateParser =   dateFormatter;
        Calendar cal = Calendar.getInstance();
        
        YESTERDAY=cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+(cal.get(Calendar.DAY_OF_MONTH)-1);
        TODAY=cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.DAY_OF_MONTH);
        TOMORROW=cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+(cal.get(Calendar.DAY_OF_MONTH)+1);
        WEEK = cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+(cal.get(Calendar.DAY_OF_MONTH)-cal.get(Calendar.DAY_OF_WEEK)+2);
        MONTH = cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-01";
         	
    	String date = dateParser.format(cal.get(Calendar.DATE));
    	return date;
    }
    
    private void copyToClipboard(){
    	ClipboardManager clipboard = (ClipboardManager)
    	        getSystemService(Context.CLIPBOARD_SERVICE);
    	clipboard.setText(cont.getText());
    }
    
    
 //internal clsses   
    class AsyncGetHoroscop extends AsyncTask<String, Void, String>{
    	ProgressDialog progress;    	 
     
        protected void onPreExecute() {
            super.onPreExecute();
            this.progress =  ProgressDialog.show(ViewPageActivity.this, "", getResources().getText(R.string.dlg_plswtng));
        }        
    	
    	protected String doInBackground(String... params) {
    		
    		String result="";
    		String u="";
    		for (int i = 0; i < params.length; i++) {
    			u = u.concat("&"+params[i]);
    			Log.d("app",u);
    		}
    		DbAction da = new DbAction(getApplicationContext(),"cache");  		
    		result = da.getFromDb(u);
    		if (result.equals("")){
    			result = GetHoroscop.get(u);
    			da.addToDb(u, result);
    		}
    		return result;
    	}    	
    		
    	protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result.contains("null"))showDialog(INET_CON);
            else cont.setText(result);
            progress.dismiss();
        }
    }
  
    
 
}